import React, { Component } from "react";
import { Link, withRouter } from "react-router-dom";
import "./index.less";
import logo from "../../assets/images/logo.png";
import { Menu, Icon } from "antd";
import menuList from "../../config/menuConfig";

const { SubMenu } = Menu;

class LeftNav extends Component {

	getMenuNodes (menuList) {
		return menuList.map(item => {
			if(!item.children) {
				return (
					<Menu.Item key={item.key}>
						<Link to={item.key}>
							<Icon type={item.icon} />
							<span>{item.title}</span>
						</Link>
					</Menu.Item>
				)
			} else{
				return(
					<SubMenu
            key={item.key}
            title={
              <span>
                <Icon type={item.icon} />
                <span>{item.title}</span>
              </span>
            }
          >
            {this.getMenuNodes(item.children)}
          </SubMenu>
				)
			}
		})
	}

	getMenuNodes_reduce (menuList) {
		let pathname = this.props.location.pathname;

		return menuList.reduce((pre, item)=>{
			if (!item.children) {
				pre.push((
					<Menu.Item key={item.key}>
					<Link to={item.key}>
						<Icon type={item.icon} />
						<span>{item.title}</span>
					</Link>
				</Menu.Item>
				))
			} else {
				let cItem = item.children.find(child => child.key === pathname);
				if(cItem){
					this.openKey = item.key;
				}
				pre.push((
						<SubMenu
							key={item.key}
							title={
								<span>
									<Icon type={item.icon} />
									<span>{item.title}</span>
								</span>
							}
						>
							{this.getMenuNodes_reduce(item.children)}
						</SubMenu>
				))
			}
			return pre
		}, [])
	}

	constructor(props){
		super(props);
		this.menuNodes = this.getMenuNodes_reduce(menuList)
	}
	
  render() {

		let pathname = this.props.location.pathname;
		let openKey = this.openKey;

    return (
      <div className="left-nav">
        <Link to="/" className="left-nav-header">
          <img src={logo} alt="logo" />
          <h2>硅谷后台</h2>
        </Link>
        <Menu selectedKeys={[pathname]} defaultOpenKeys={[openKey]} mode="inline" theme="dark">
					{
						this.menuNodes
					}
        </Menu>
      </div>
    );
  }
}

export default withRouter(LeftNav)